<template>
  <div v-show="allTypes.length > 0">
    <el-select
      placeholder="请选择统计类型"
      v-model="selectedType"
      value-key="id"
      @change="selectedTypeChange"
    >
      <el-option
        v-for="type in allTypes"
        :key="type.id"
        :value="type"
        :label="type.name"
      ></el-option>
    </el-select>
    <div v-show="showChart === SHOWSTATUS.NODATA">该类型暂无数据</div>
    <div v-show="showChart === SHOWSTATUS.SHOW" id="mychartbar"></div>
    <div v-show="showChart === SHOWSTATUS.SHOW" id="mychartline"></div>
    <div v-show="showChart === SHOWSTATUS.SHOW" id="mychartcal"></div>
  </div>
  <div v-show="allTypes.length == 0">
    您还没有可以统计的数据类型，请您先前往【类别管理】添加数据。
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import { listDataRange } from "/@/util/api";
import getAllTypes from "/@/composables/getAllTypes";
import { echarts, ECOption } from "/@/util/myEchart";
export default defineComponent({
  setup() {
    // =====图表初始化=====
    // 柱形图OPTION
    var optionBar: ECOption = {
      title: {
        text: "过往一年数据月份排行",
      },
      tooltip: {
        textStyle: {
          fontSize: 12,
        },
      },
      grid: {
        left: 50,
      },
      xAxis: { type: "value", axisLabel: { fontSize: 12 } },
      yAxis: { type: "category", axisLabel: { fontSize: 12 } },
      series: {
        name: "排行",
        type: "bar",
        data: [],
      },
    };
    // 线型图OPTION
    let optionLine: ECOption = {
      title: {
        text: "过往一年数据月份趋势",
      },
      tooltip: {
        textStyle: {
          fontSize: 12,
        },
      },
      grid: {
        left: 50,
      },
      xAxis: { type: "category", axisLabel: { fontSize: 12 } },
      yAxis: { type: "value", axisLabel: { fontSize: 12 } },
      series: {
        name: "趋势",
        type: "line",
        symbol: "circle",
        symbolSize: 16,
        data: [],
      },
    };
    // 热力图OPTION
    let optionCalendar = {
      title: {
        text: "过往一年每日数据",
      },
      tooltip: {
        formatter: "{c}",
        textStyle: {
          fontSize: 12,
        },
      },
      visualMap: {
        top: 100,
        right: 30,

        min: 0,
        max: 10,
        type: "piecewise",
        orient: "vertical",
        inRange: {
          color: ["#C7DBFF", "#5291FF"],
        },
        textStyle: {
          color: "#000",
          fontSize: 12,
        },
      },
      calendar: {
        top: 100,
        bottom: 20,
        left: 50,
        right: 50,
        orient: "vertical",
        cellSize: ["auto", "auto"],
        range: ["2016"],
        itemStyle: {
          borderWidth: 1,
        },
        yearLabel: { show: false },
        dayLabel: {
          firstDay: 1, // 从周一开始
          nameMap: "cn",
          fontSize: 12,
        },
        monthLabel: {
          nameMap: "cn",
          fontSize: 12,
        },
      },
      series: {
        type: "heatmap",
        coordinateSystem: "calendar",
        data: [],
      },
    };
    let myChartBar: echarts.ECharts; // 柱状图
    let myChartLine: echarts.ECharts; // 线型图
    let myChartCalendar: echarts.ECharts; // 日历图
    function initCharts() {
      myChartBar = echarts.init(
        document.getElementById("mychartbar") as HTMLElement
      );
      myChartBar.setOption(optionBar);
      myChartLine = echarts.init(
        document.getElementById("mychartline") as HTMLElement
      );
      myChartLine.setOption(optionLine);
      myChartCalendar = echarts.init(
        document.getElementById("mychartcal") as HTMLElement
      );
      myChartCalendar.setOption(optionCalendar);
    }
    onMounted(() => {
      initCharts();
    });

    // 获得相对应类型近一年的数据
    let oneYearData: { [key: string]: any } = { total: 0 };
    function getDataOfTypeY(typeId: number) {
      let today = new Date();
      let todayDate = today.toLocaleDateString();
      let lastYearDate = new Date(
        today.getFullYear() - 1,
        today.getMonth() - 1,
        1
      );
      listDataRange({
        typeId: typeId,
        beginDate: lastYearDate,
        endDate: todayDate,
      })
        .then((res) => {
          let dataY = res.data; // 一年份的数据
          console.log("dataY", dataY);
          if (dataY.length === 0) {
            showChart.value = SHOWSTATUS.NODATA;
            return;
          }
          let dataObj: { [key: string]: any } = { total: 0 }; // { 年：{月：{日：值}}}
          let dataForCalendar = [];
          let dataForCalendarMap: { [key: string]: any } = {};
          console.log(res);
          for (let item of dataY) {
            if (!dataForCalendarMap[item.date as string]) {
              console.log(item.value);
              dataForCalendarMap[item.date as string] = item.value;
            } else {
              dataForCalendarMap[item.date as string] += item.value;
            }
            //   dataForCalendar.push([item.date, +(item.value as number)]);
            let [y, m, d] = (item.date as string).split("/");
            if (!dataObj[y]) dataObj[y] = { total: 0 };
            if (!dataObj[y][m]) dataObj[y][m] = { total: 0 };
            if (!dataObj[y][m][d]) dataObj[y][m][d] = 0;
            dataObj[y][m][d] += Number(item.value);
            dataObj[y][m]["total"] += Number(item.value);
            dataObj[y]["total"] += Number(item.value);
            dataObj["total"] += Number(item.value);
          }

          oneYearData.total = dataObj["total"];
          dataForCalendar = Object.keys(dataForCalendarMap).map((x) => {
            return [x, dataForCalendarMap[x]];
          });
          let dataBar = [];
          let dataLine = [];
          for (let i in dataObj) {
            if (i === "total") continue;
            for (let j in dataObj[i]) {
              if (j === "total") continue;
              // 折线图数据
              dataLine.push([`${i.slice(-2)}年${j}`, dataObj[i][j]["total"]]);
              // 柱状图数据
              dataBar.push([dataObj[i][j]["total"], `${i.slice(-2)}年${j}`]);
              // 对柱状图排序
              dataBar.sort((x, y) => {
                return y[0] - x[0];
              });
              oneYearData.highestM = dataBar[0][1].split("年")[1];
              oneYearData.highest = dataBar[0][0];
            }
          }
          console.log("oneYearData", oneYearData);
          myChartBar.setOption({
            yAxis: {
              data: dataBar.map((x) => {
                return x[1];
              }),
            },
            series: {
              type: "bar",
              data: dataBar,
            },
          });
          myChartLine.setOption({
            xAxis: {
              data: dataLine.map((x) => {
                return x[0];
              }),
            },
            series: {
              type: "line",
              data: dataLine,
            },
          });
          myChartCalendar.setOption({
            calendar: {
              range: [lastYearDate, todayDate],
            },
            visualMap: {
              max: dataBar[0][0],
            },
            series: {
              type: "heatmap",
              coordinateSystem: "calendar",
              data: dataForCalendar,
            },
          });
          showChart.value = SHOWSTATUS.SHOW;
        })
        .catch((e) => {
          console.log(e);
        });
    }

    // =====选择统计类型逻辑=====
    enum SHOWSTATUS {
      HIDDEN,
      SHOW,
      NODATA,
    }
    const { allTypes } = getAllTypes();
    let showChart = ref(SHOWSTATUS.HIDDEN);
    let selectedType = ref(null);
    function selectedTypeChange(type: any) {
      console.log("selectedType", selectedType.value);
      getDataOfTypeY(type.id);
    }
    return {
      allTypes,
      selectedType,
      selectedTypeChange,
      showChart,
      SHOWSTATUS,
    };
  },
});
</script>
<style lang="scss" scoped>
#mychartbar,
#mychartline {
  width: 100vw;
  height: 80vw;
}
#mychartcal {
  width: 100vw;
  height: 240vw;
}
</style>
